#include "MainWindow.h"
#include "gecabol.h"
#include <QtGui>
#include <QSqlDatabase>
#include <QSqlError>
#include <iostream>
#include <QSqlQuery>

GECABOL::GECABOL(QWidget *parent)
    : QDialog(parent)
{
	 userLabel = new QLabel("Usuario: ");
	 passwordLabel = new QLabel("Contrasena: ");
	 user = new QLineEdit;
	 password = new QLineEdit;
	 ok = new QPushButton("Aceptar");
	 cancel = new QPushButton("Cancelar");
	    
	 userLabel->setBuddy(user);
	 passwordLabel->setBuddy(password);
	 password->setEchoMode(QLineEdit::Password);

	 QGridLayout *mainLayout = new QGridLayout;
	 QHBoxLayout *buttonLayout = new QHBoxLayout;
	 mainLayout->addWidget(userLabel,0,0);
	 mainLayout->addWidget(user,0,1);
	 mainLayout->addWidget(passwordLabel,1,0);
	 mainLayout->addWidget(password,1,1);
	 
	 buttonLayout->addWidget(ok);
	 buttonLayout->addWidget(cancel);
	 mainLayout->addLayout(buttonLayout,2,0,1,2,Qt::AlignHCenter);
	 setLayout(mainLayout);
	 setWindowTitle("Login");
	 setFixedHeight(120);
	 this->setFixedWidth(250);
	 connect(cancel,SIGNAL(clicked()),this, SLOT(close()));
	 //connect(ok,SIGNAL(clicked()),this,SLOT(showMainWindow()));
	 connect(ok,SIGNAL(clicked()),this,SLOT(validateUser()));
	 setVisible(true);
}

void GECABOL::showMainWindow(int perf){
	
	mainWindow = new MainWindow(perf);
	mainWindow->show();
	close();
}

bool GECABOL::connectDB(){
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); 
	db.setHostName("192.168.1.76"); 
	db.setPort(3306);
	db.setDatabaseName("Gecabol"); 
	db.setUserName("Rodrigo"); 
	db.setPassword("rdrik"); 
	if (!db.open()) { 
	    QMessageBox::critical(0, QObject::tr("Database Error"), 
	                          db.lastError().text()); 
	    return false; 
	} 
	    return true; 
		
}

int GECABOL::validateUser(){
	QString usertext= user->text();
	QString pass=password->text();
	int perfil;
	QString qery="SELECT idPerfil FROM Usuario WHERE nombreUsuario ='"+usertext+"' AND"+
	              " password = '"+pass+"'"; 
	QSqlQuery query;
	
	query.exec(qery);
	if(query.next()){//Se encontro un usuario coincidente.Autenticado
		std::cerr << qPrintable(qery) <<std::endl;
		perfil=query.value(0).toInt();
		showMainWindow(perfil);
	}else
	QMessageBox::critical(0, QObject::tr("Error"),"Revise su nombre de usuario/contraseña"); 
	//std::cout << "sd" << std::endl;
	return perfil;
	
}

GECABOL::~GECABOL()
{

}
